import request from '@/api/request'
import type { LoginForm, LoginResponse, RegisterForm, User } from '@/services/account/account.types'
import { useAccountStore } from '@/stores/account'

export default class AccountService {
  async login(form: LoginForm): Promise<void> {
    const response = await request.post<LoginResponse>('/as/account/login', form)
    const authStore = useAccountStore()
    authStore.setTokens(response.data)
    await this.getUserInfo()
  }

  async register(form: RegisterForm): Promise<string> {
    const response = await request.post<{ data: string }>('/as/account/register', form)
    return response.data.data
  }

  async logout(): Promise<void> {
    await request.get<{ data: string }>('/as/account/logout')
    const authStore = useAccountStore()
    authStore.clearAuth()
  }

  async refreshToken(refreshToken: string): Promise<LoginResponse> {
    const response = await request.post<LoginResponse>('/as/account/token/refresh', refreshToken)
    return response.data
  }

  async getUserInfo(): Promise<void> {
    const response = await request.get<{ data: User }>('/as/account/info')
    const accountStore = useAccountStore()
    accountStore.setUser(response.data.data)
  }

  async updatePassword(oldPassword: string, newPassword: string): Promise<void> {
    await request.put('/as/account/password', {
      oldPassword,
      newPassword,
    })
  }

  async updateUserInfo(user: Partial<User>): Promise<void> {
    await request.put('/as/account/info', user)
    await this.getUserInfo()
  }
}
